package com.taxshare.tools.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelWriter;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author YANG
 * @date 2021/3/17
 */
@Slf4j
public class ExcelUtil {
    public static void exportExcel(HttpServletResponse response, List<String> cols, Map<String, String> header, List data, String fileName) throws Exception {
        ExcelWriter writer = null;
        ServletOutputStream out = null;
        try {
            writer = cn.hutool.poi.excel.ExcelUtil.getWriter();
            fileName = fileName + "_" + new String(
                    (new SimpleDateFormat("yyyy-MM-dd").format(new Date())).getBytes(), "UTF-8");
            for (String col : cols) {
                writer.addHeaderAlias(col, header.get(col));
            }
            writer.write(data, true);
            writer.setColumnWidth(-1,25);
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xlsx", "utf-8"));
            out = response.getOutputStream();
            writer.flush(out, true);
        } catch (Exception e) {
            throw e;
        } finally {
            // 关闭writer，释放内存
            writer.close();
            IoUtil.close(out);
        }

    }


    /**
     * 读取Excel信息
     *
     * @param in
     * @param t
     * @param <R>
     * @param <T>
     * @return
     */
    public static <R, T> List<T> readExcel(InputStream in, R r,Class<T> t) {
        ExcelReader reader = cn.hutool.poi.excel.ExcelUtil.getReader(in);
        headerAlias(r, reader);
        try {
            return reader.readAll(t);
        } catch (Exception e) {
            log.error("读取Excel异常,{}", e);
            return new ArrayList<>();
        }
    }

    /**
     * 设置Excel读取配置
     *
     * @param header
     * @param reader
     * @param <T>
     * @return
     */
    private static <T> ExcelReader headerAlias(T header, ExcelReader reader) {
        Map<String, Object> tmpMap = BeanUtil.beanToMap(header) ;
        if(MapUtil.isEmpty(tmpMap)){
            tmpMap = MapUtil.newHashMap();
        }
        final Iterator<Map.Entry<String, Object>> it = tmpMap.entrySet().iterator();
        Map.Entry<String, Object> entry;
        while (it.hasNext()) {
            entry = it.next();
            if (!StringUtil.isEmpty(entry.getValue())) {
                reader.addHeaderAlias(StrUtil.toString(entry.getValue()), entry.getKey());
            }
        }
        return reader;
    }

}
